package com.dingwen.minsta.service.impl;

import com.dingwen.minsta.service.TempService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.File;

/**
 * temp service impl
 *
 * @author dingwen
 * 2021.05.27 17:19
 */
@Service
public class TempServiceImpl implements TempService {
    @Override
    public void cleanTemp(String tempDir, Long tempAliveDuration) {
        File dir = new File(tempDir);

        if (dir.exists() && dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (!ObjectUtils.isEmpty(files)) {
                long currentTime = System.currentTimeMillis();
                for (File file : files) {
                    long lastModified = file.lastModified();
                    if (file.canWrite() && (currentTime - lastModified >= tempAliveDuration)) {// 文件最后一次修改距离现在时间超过存活时间
                        boolean flag = file.delete();
                    }
                }
            }
        }
    }
}
